package auto.app.util;

import auto.app.controller.info.ConnecitonInfo.ConnectionConfiguraDetailInfo;
import auto.app.exetion.MainExection;
import auto.app.model.DatabaseConnect;
import auto.app.service.ConnectionConfigurationService;
import auto.app.service.DatabaseConnectService;
import auto.app.vo.MysqlReturn;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static auto.app.exetion.MainExetionMessage.*;

@Slf4j
@Component
@AllArgsConstructor
public class MysqlUtil {
    ConnectionConfigurationService connectionConfigurationService;
    DatabaseConnectService databaseConnectService;

    //返回DriverManagerDataSource
    public DriverManagerDataSource mysqlConnection(ConnectionConfiguraDetailInfo connectionConfiguraDetailInfo){
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        //设置驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        String url="";
        //设置链接地址 端口 密码
        if (ObjectUtil.isNotNull(connectionConfiguraDetailInfo.getConnectionPort())){
            url="jdbc:mysql://"+connectionConfiguraDetailInfo.getConnectionIp()+":"+connectionConfiguraDetailInfo.getConnectionPort()+"/"+connectionConfiguraDetailInfo.getConnectionDatabase();
        }else{
            url="jdbc:mysql://"+connectionConfiguraDetailInfo.getConnectionIp()+"/"+connectionConfiguraDetailInfo.getConnectionDatabase();
        }
        String urlNew=url+"?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&autoReconnect=true&serverTimezone=UTC";
        dataSource.setUrl(urlNew);
        dataSource.setUsername(connectionConfiguraDetailInfo.getConnectionUsername());
        if (ObjectUtil.isNotNull(connectionConfiguraDetailInfo.getConnectionPassword())){
            dataSource.setPassword(connectionConfiguraDetailInfo.getConnectionPassword());
        }else{
            dataSource.setPassword("");
        }
        return dataSource;
    }

    /**
     * 执行方法
     * @param databaseId
     * @throws MainExection
     */
    public MysqlReturn excult(String databaseId) throws MainExection {
        //查询数据库操作是否存在
        DatabaseConnect byId = databaseConnectService.getById(databaseId);
        if (ObjectUtil.isNull(byId)){
            throw new MainExection(DATABASECAOZUOERROR.getCode(),DATABASECAOZUOERROR.getMsg());
        }
        //查询数据库练级是否存在
        ConnectionConfiguraDetailInfo connectionConfiguraDetailInfo = connectionConfigurationService.ConnectionConfigurationDetail(byId.getConnectionId());
        if (ObjectUtil.isNull(connectionConfiguraDetailInfo)){
            throw new MainExection(CONNECTIONSLECTERROR.getCode(),CONNECTIONSLECTERROR.getMsg());
        }
        //执行方法判断走哪个类型
        if (ObjectUtil.isNotNull(byId.getSqlType())){
            DriverManagerDataSource driverManagerDataSource = mysqlConnection(connectionConfiguraDetailInfo);
            JdbcTemplate jdbcTemplate=new JdbcTemplate(driverManagerDataSource);
            String sql=byId.getDatabaseSql();
            Object sqlExcultResult=null;
            try {
                switch (byId.getSqlType()){
                    case "insert":
                        sqlExcultResult=jdbcTemplate.update(sql);;
                        String s4 = JSONUtil.toJsonStr(sqlExcultResult);
                        return MysqlReturn.builder().code(200).msg("数据库操作执行成功").result(s4).build();
                    case "update":
                        sqlExcultResult = jdbcTemplate.update(sql);
                        String s3 = JSONUtil.toJsonStr(sqlExcultResult);
                        return MysqlReturn.builder().code(200).msg("数据库操作执行成功").result(s3).build();
                    case "select":
                        sqlExcultResult = jdbcTemplate.queryForList(sql);
                        String s2 = JSONUtil.toJsonStr(sqlExcultResult);
                        return MysqlReturn.builder().code(200).msg("数据库操作执行成功").result(s2).build();
                    case "delete":
                        sqlExcultResult = jdbcTemplate.update(sql);
                        String s1 = JSONUtil.toJsonStr(sqlExcultResult);
                        return MysqlReturn.builder().code(200).msg("数据库操作执行成功").result(s1).build();
                    default:
                        throw new MainExection(SQLTYPEERROR.getCode(),SQLTYPEERROR.getMsg());
                }
            }catch (Exception e){
                return MysqlReturn.builder().code(200).msg("数据库操作执行失败").result(e.getMessage()).build();
            }
        }else{
            throw new MainExection(SQLTYPEERROR.getCode(),SQLTYPEERROR.getMsg());
        }
    }


}
